#include "pthreadPool.h"

void * threadFunc(void *arg){
    threadPool_t *pthreadPool = (threadPool_t*)arg;
    server_t *pserver;
    while(1){
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->flag == 0 && pthreadPool->taskQueue.queueSize <= 0){
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        if(pthreadPool->flag == 1){
            pthread_mutex_unlock(&pthreadPool->mutex);
            pthread_exit(NULL);
        }
        pserver = pthreadPool->taskQueue.pFront->pserver;
        /* deQueue(&pthreadPool->taskQueue); */
        task_t *pTask = pthreadPool->taskQueue.pFront;
        pthreadPool->taskQueue.pFront = pTask->pNext;
        if(pthreadPool->taskQueue.queueSize == 1){
            pthreadPool->taskQueue.pRear = NULL;
        }
        --pthreadPool->taskQueue.queueSize;
        free(pTask);  // 只释放task_t，不释放server_t
        pthread_mutex_unlock(&pthreadPool->mutex);
        //do_sth
        printf("DEBUG: Worker thread got pserver->userName = '%s'\n", pserver->userName);
        handleLongCmd(pserver);
        
        free(pserver);
        printf("Done.\n");
    }
    return NULL;
}
int makeWorker(threadPool_t *pthreadPool){
    for(int i = 0;i < pthreadPool->tidArr.workerNum;++i){
        pthread_create(&pthreadPool->tidArr.pthreadTid[i],NULL,threadFunc,pthreadPool);
    }
    printf("Here are %d workers.\n",pthreadPool->tidArr.workerNum);
    return 0;
}
